﻿using AutoMapper;
using ERPPublic;
using FinancialManagement.Application.Command.SalesShouldRefundCommand;
using FinancialManagement.Domain.Dto;
using FinancialManagement.Domain.Model;
using FinancialManagement.Infrstructre.Interface;
using MediatR;
using Newtonsoft.Json;
using SqlSugar;
using System.Collections.Generic;
using static ERPPublic.ParseAPI;

namespace FinancialManagement.Application.CommandHandler.SalesShouldRefundCommandHandler
{
    public class AddSalesShouldRefundCommandHandler : IRequestHandler<AddSalesShouldRefundCommand, int>
    {
        ISalesShouldRefundRepository ssrRep;
        ISalesReturnRepository srRep;
        ISqlSugarClient db;

        public AddSalesShouldRefundCommandHandler(ISalesShouldRefundRepository ssrRep, ISalesReturnRepository srRep, ISqlSugarClient db)
        {
            this.ssrRep = ssrRep;
            this.srRep = srRep;
            this.db = db;
        }

        public async Task<int> Handle(AddSalesShouldRefundCommand request, CancellationToken cancellationToken)
        {
            // 开始事务
            db.Ado.BeginTran();

            try
            {
                //添加
                var list = await ssrRep.AddAsync(new SalesShouldRefund
                {
                    SalesShouldRefundId = request.SalesShouldRefundId,
                    RefundPlanCode = Guid.NewGuid().ToString(),
                    PlanRefundDate = request.PlanRefundDate,
                    AmountRefund = request.AmountRefund,
                    RefundPaceWay = request.RefundPaceWay,
                    SalesReturnId = request.SalesReturnId,
                });

                List<Client> clients = await GetClientList("", "", null, null, 0, "", 0, 1, 1000);
                var salesreturn = (from sr in await srRep.GetAllAsyns() select sr).ToList();
                var salesshould = (from ssr in await ssrRep.GetAllAsyns() select ssr).ToList();
                var fan = (from sr in salesreturn
                           //join c in clients on sr.ClientId equals c.ClientId
                           where sr.SalesReturnId== request.SalesReturnId
                           select new SalesReturn
                           {
                                SalesReturnId = sr.SalesReturnId,
                                SalesReturnCode = sr.SalesReturnCode,
                                SalesReturnTopic = sr.SalesReturnTopic,
                                SalesReturnDate = sr.SalesReturnDate,
                                ClientId = sr.ClientId,
                                SalesReturnState = sr.SalesReturnState,
                                SalesReturnAmout = sr.SalesReturnAmout,
                                //ClientName = c.ClientName,
                           }).First();

                fan.SalesReturnAmout -= request.AmountRefund;
                await srRep.UpdateAsync(fan);



                // 提交事务
                db.Ado.CommitTran();

                return 1;  // 返回最终的结果
            }
            catch (Exception)
            {
                // 回滚事务
                db.Ado.RollbackTran();
                throw;
            }
        }



        /// <summary>
        /// 显示客户信息
        /// </summary>
        /// <param name="ClientName"></param>
        /// <param name="CRecipients"></param>
        /// <param name="STime"></param>
        /// <param name="ETime"></param>
        /// <param name="CPickingStatus"></param>
        /// <param name="CApplicant"></param>
        /// <param name="CIndustry"></param>
        /// <param name="pindex"></param>
        /// <param name="psize"></param>
        /// <returns></returns>
        public async Task<dynamic> GetClientList(string? ClientName, string? CRecipients, DateTime? STime, DateTime? ETime, int? CPickingStatus, string? CApplicant, int? CIndustry, int pindex, int psize)
        {
            string token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI1MCIsInNpZCI6IjE4NjcwOTU3MzQ0NjIwNTg0OTYiLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL2dyb3Vwc2lkIjoiMTksMTkiLCJqdGkiOiI1MGYyMWRmZS0yNWQ3LTQ1OTQtOTg1Yi0wZTM2MDhhZjJiNmYiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoi5LuY5rSb5ZiJIiwiaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvd3MvMjAwNS8wNS9pZGVudGl0eS9jbGFpbXMvdXJpIjoiLyIsImlzcyI6IlJlbmFvYm8yMDA0IiwiYXVkIjoiV2VpZnV3dTIyMDNBIn0._wh23n1M7asMGST9NyeZj-5rk5ICAiOFv6yDk6e2o7Y";
            HttpClientWrapper cilent = new HttpClientWrapper(token);

            string kehu = "http://116.205.121.197:8000/vendor/api/Client/ClientAllShow?ClientName=" + ClientName + "&CRecipients=" + CRecipients + "&STime=" + STime + "&ETime=" + ETime + "&CPickingStatus=&CApplicant=" + CApplicant + "&CIndustry=&pageIndex=" + pindex + "&pageSize=" + psize;

            string postReponse = await cilent.GetAsync(kehu);
            var json = JsonConvert.DeserializeObject<ApiResultList<Client>>(postReponse);
            return json.data.list;
        }

        /// <summary>
        /// 客户
        /// </summary>
        public class Client
        {
            /// <summary>
            ///客户id
            /// </summary>
            public int ClientId { get; set; }
            /// <summary>
            /// 客户名称
            /// </summary>
            public string? ClientName { get; set; }
            /// <summary>
            /// 客户编号
            /// </summary>
            public string? ClientNumber { get; set; }
            /// <summary>
            /// 客户类别id
            /// </summary>
            public int? CId { get; set; }
            /// <summary>
            /// 跟进方式
            /// </summary>
            public int? CFUmanner { get; set; }
            /// <summary>
            /// 所在省份
            /// </summary>
            public int? ProvinceId { get; set; }
            /// <summary>
            /// 所在城市
            /// </summary>
            public int? CityId { get; set; }
            /// <summary>
            /// 来源途径
            /// </summary>
            public int? CSourceWay { get; set; }
            /// <summary>
            /// 所属行业
            /// </summary>
            public int? CIndustry { get; set; }
            /// <summary>
            /// 客户价值
            /// </summary>
            public int? CustomerValue { get; set; }
            /// <summary>
            /// 信用等级
            /// </summary>
            public int? CreditRating { get; set; }
            /// <summary>
            /// 公司地址
            /// </summary>
            public string? CompanyAddress { get; set; }
            /// <summary>
            /// 公司简介
            /// </summary>
            public string? CompanyProfile { get; set; }
            /// <summary>
            /// 主要联系人姓名
            /// </summary>
            public string? CPrimaryContact { get; set; }
            /// <summary>
            /// 性别
            /// </summary>
            public string? CGender { get; set; }
            /// <summary>
            /// 部门
            /// </summary>
            public int? CDepartment { get; set; }
            /// <summary>
            /// 手机号码
            /// </summary>
            public string? CPhone { get; set; }
            /// <summary>
            /// 领料状态
            /// </summary>
            public int? CPickingStatus { get; set; } = 1;
            /// <summary>
            /// 申请人
            /// </summary>
            public string? CApplicant { get; set; }
            /// <summary>
            /// 领用人
            /// </summary>
            public string? CRecipients { get; set; }
            /// <summary>
            /// 领用时间
            /// </summary>
            public DateTime? CPickTime { get; set; }
        }


    }
}
